package p.ithorns.integration.hazelcast.map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hazelcast.map.MapStore;
import lombok.extern.slf4j.Slf4j;
import p.ithorns.integration.db.entity.User;
import p.ithorns.integration.db.mapper.UserMapper;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * MapStoreImpl
 *
 * @author Ht.L
 * @date 2023-10-18 10:08
 * @since 1.0.0
 */
@Slf4j
public class MapStoreImpl implements MapStore<Integer, User> {

    private UserMapper userMapper;

    public MapStoreImpl() {
    }

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void store(Integer key, User value) {
        userMapper.updateById(value);
        log.info("====> store: {}", value);
    }

    @Override
    public void storeAll(Map<Integer, User> map) {
        Collection<User> values = map.values();
        userMapper.insertBatch(values);
        log.info("====> storeAll: {}", values);
    }

    @Override
    public void delete(Integer key) {
        userMapper.deleteById(key);
        log.info("====> delete: {}", key);
    }

    @Override
    public void deleteAll(Collection<Integer> keys) {
        userMapper.deleteBatchIds(keys);
        log.info("====> deleteAll: {}", keys);
    }

    @Override
    public User load(Integer key) {
        User user = userMapper.selectById(key);
        log.info("====> load: {} -> {}", key, user);
        return user;
    }

    @Override
    public Map<Integer, User> loadAll(Collection<Integer> keys) {
        List<User> users = userMapper.selectBatchIds(keys);
        log.info("====> loadAll: {} ", users);
        return users.stream().collect(Collectors.toMap(User::getId, v -> v, (v1, v2) -> v2));
    }

    @Override
    public Iterable<Integer> loadAllKeys() {
        QueryWrapper<User> qw = Wrappers.<User>query().select("id");
        List<User> users = userMapper.selectList(qw);

        Set<Integer> collect = users.stream().map(User::getId).collect(Collectors.toSet());
        log.info("====> loadAllKeys: {} ", collect);
        return collect;
    }
}